//
//  ZKWKWebViewController.m
//  StudentKudou
//
//  Created by 赵坪生 on 2017/5/11.
//  Copyright © 2017年 赵坪生. All rights reserved.
//

#import "ZKWKWebViewController.h"
#import "ZKWKUserContentController.h"
//#import "ZKShareAdapter.h"
//#import "WMDragView.h"
@interface ZKWKWebViewController ()<WKUIDelegate, WKNavigationDelegate>
@property(nonatomic, strong)WKWebView * webView;
@property(nonatomic, strong)UIProgressView *progressView;
@property(nonatomic, strong)UIButton *goBtn;
@property(nonatomic,strong)NSTimer *globalTimer;
@property(nonatomic,assign)NSInteger time;
@end

@implementation ZKWKWebViewController

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self onBack];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(self.isMain){
        self.navigationController.navigationBar.hidden = YES;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.time = 0;
    self.navigationItem.title  = self.myTitle;
    DEFINE_WEAK(self)
    WKWebViewConfiguration * configuration = [[WKWebViewConfiguration alloc] init];
    configuration.userContentController = [[ZKWKUserContentController alloc] initWithViewController:wself];
    self.webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
    [self.view addSubview:self.webView];
    if(!self.isShowSave){
        [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.bottom.equalTo(wself.view);
        }];
    }
    
   
   
    
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    assert(self.url || self.html);
    if (self.url) {
        NSURL * url = [NSURL URLWithString:self.url];
        [self.webView loadRequest:[[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30]];
    }else{

        if(self.isShowSave){
                    NSString * resourcePath = [ [NSBundle mainBundle] resourcePath];
                    [self.webView loadHTMLString:self.html baseURL:[NSURL fileURLWithPath:resourcePath]];
        }else{
            NSString *path = [[NSBundle mainBundle] pathForResource:self.html ofType:@"png"];
               NSURL *url = [NSURL fileURLWithPath:path];
           //    self.webView = [[WKWebView alloc] initWithFrame:webRect];
               [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
        }
      
    }
    
    self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    self.progressView.progressTintColor = [UIColor blueColor];
    [self.webView addSubview:self.progressView];
  
        [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(wself.webView);
            make.height.mas_equalTo(2);
        }];
  
   
    
    //监听estimatedProgress进度 ，原生title
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
    
    if (self.isShowSave) {
        [self addRigtNav];
        self.view.backgroundColor = rgb(243, 246, 254);
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        headerView.backgroundColor = [UIColor whiteColor];
        headerView.layer.masksToBounds = YES;
        headerView.layer.cornerRadius = 8;
        [self.view addSubview:headerView];
        [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(wself.view.mas_top).offset(10);
            make.height.mas_equalTo(@230);
            make.left.mas_equalTo(wself.view.mas_left).offset(10);
            make.right.mas_equalTo(wself.view.mas_right).offset(-10);
        }];

        NSString *icon = [NSString stringWithFormat:@"%@",self.savaDict[@"image"]];
        UIImageView * headerImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:icon]];
        headerImageView.userInteractionEnabled = YES;
        headerImageView.backgroundColor = [UIColor clearColor];
        headerImageView.layer.masksToBounds = YES;
        headerImageView.layer.cornerRadius = 8;
        [headerView addSubview:headerImageView];
        [headerImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(headerView.mas_top).offset(10);
            make.left.mas_equalTo(headerView.mas_left).offset(10);
            make.right.mas_equalTo(headerView.mas_right).offset(-10);
            make.height.mas_equalTo(140);
        }];

//        UILabel * Label1 = [UILabel new];
//        Label1.numberOfLines = 1;
//        Label1.text = [NSString stringWithFormat:@"类型：%@",self.savaDict[@"type"]];
//        Label1.textColor = [UIColor blackColor];
//        Label1.font = [UIFont systemFontOfSize:15 weight:UIFontWeightBold];
//        [headerView addSubview:Label1];
//        [Label1 mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.mas_equalTo(headerImageView.mas_bottom).offset(20);
//            make.left.mas_equalTo(headerImageView.mas_left).offset(0);
////            make.right.mas_equalTo(detailview.mas_right).offset(-100);
//            make.height.mas_equalTo(20);
//        }];
//
        UILabel * Label2 = [UILabel new];
        Label2.numberOfLines = 1;
        Label2.text = [NSString stringWithFormat:@"日期：%@",self.savaDict[@"time"]];
        Label2.textColor = [UIColor blackColor];
        Label2.font = [UIFont systemFontOfSize:15 weight:UIFontWeightBold];
        [headerView addSubview:Label2];
        [Label2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(headerImageView.mas_bottom).offset(15);
            make.left.mas_equalTo(headerImageView.mas_left).offset(0);
//            make.right.mas_equalTo(detailview.mas_right).offset(-100);
            make.height.mas_equalTo(20);
        }];
        
        
        UILabel * Label3 = [UILabel new];
        Label3.numberOfLines = 1;
        Label3.text = [NSString stringWithFormat:@"作者：%@",@"匿名"];
        Label3.textColor = [UIColor blackColor];
        Label3.font = [UIFont systemFontOfSize:15 weight:UIFontWeightBold];
        [headerView addSubview:Label3];
        [Label3 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(Label2.mas_bottom).offset(15);
            make.left.mas_equalTo(headerImageView.mas_left).offset(0);
//            make.right.mas_equalTo(detailview.mas_right).offset(-100);
            make.height.mas_equalTo(20);
        }];
        
//        UILabel * Label4 = [UILabel new];
//        Label4.numberOfLines = 1;
//        Label4.text = @"详细内容:";
//        Label4.textColor = [UIColor blackColor];
//        Label4.font = [UIFont systemFontOfSize:18 weight:UIFontWeightBold];
//        [headerView addSubview:Label4];
//        [Label4 mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.mas_equalTo(Label3.mas_bottom).offset(15);
//            make.left.mas_equalTo(headerImageView.mas_left).offset(0);
////            make.right.mas_equalTo(detailview.mas_right).offset(-100);
//            make.height.mas_equalTo(20);
//        }];-
        
        
        UILabel * Label5 = [UILabel new];
        Label5.textAlignment = NSTextAlignmentCenter;
        Label5.numberOfLines = 1;
        Label5.text = @"点击分享";
        Label5.textColor = [UIColor whiteColor];
        Label5.backgroundColor = [UIColor colorWithHexString:APP_tab_Color];
        Label5.font = [UIFont systemFontOfSize:12 weight:UIFontWeightBold];
        [headerView addSubview:Label5];
        Label5.layer.masksToBounds = YES;
        Label5.layer.cornerRadius = 15;
        [Label5 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(headerImageView.mas_bottom).offset(25);
            make.right.mas_equalTo(headerImageView.mas_right).offset(-10);
//            make.right.mas_equalTo(detailview.mas_right).offset(-100);
            make.height.mas_equalTo(30);
            make.width.mas_equalTo(70);
        }];
        Label5.userInteractionEnabled = YES;
        [Label5 bk_whenTapped:^{
            [self share];
        }];
        
        
        self.progressView.hidden = YES;
        
        
        self.webView.layer.masksToBounds = YES;
        self.webView.layer.cornerRadius = 8;
        [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(headerView.mas_bottom).offset(10);
//            make.left.right.equalTo(wself.view);
            make.left.mas_equalTo(headerView.mas_left).offset(0);
            make.right.mas_equalTo(headerView.mas_right).offset(-0);
            make.bottom.equalTo(wself.view.mas_bottom).offset(-50);
        }];

        UIButton *close = [UIButton buttonWithType:UIButtonTypeCustom];
        self.goBtn = close;
        [close setBackgroundColor:[UIColor colorWithHexString:Navigation_And_StatusBar_Color]];
        [close setFrame:CGRectMake(0, 0, 40, 30)];
        [close setTitle:@"学习中..." forState:UIControlStateNormal];
        close.titleLabel.font = [UIFont boldSystemFontOfSize:18];
        [close setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.view addSubview:close];
        [self.goBtn mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(wself.view);
            make.height.mas_equalTo(50);
        }];
        
    }
    
    if(self.isMain){
        [self.webView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(wself.view);
            make.top.equalTo(wself.view.mas_top).offset(40);
        }];
    }
//    self.dragView.backgroundColor = [UIColor redColor];
//    [self.view bringSubviewToFront:self.dragView];
}

-(void)addTimer{
    self.globalTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(globalTimeIsUp) userInfo:nil repeats:YES];
}

-(void)globalTimeIsUp{
    self.time = self.time + 1;
    NSString *timeStr = [NSString stringWithFormat:@"学习中:%lds",(long)self.time];
    self.goBtn.titleLabel.text = timeStr;
    [self.goBtn setTitle:timeStr forState:UIControlStateNormal];
}

-(void)addRigtNav{
    NSMutableArray *array1 = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"MyData"]];;
    BOOL flag = NO;
    if(array1){
        for (NSDictionary *dict in array1) {
            if([dict[@"title"] isEqualToString:self.savaDict[@"title"]]){
                flag = YES;
            }
        }
    }
    
    
    
   UIButton *close = [UIButton buttonWithType:UIButtonTypeCustom];
   [close setFrame:CGRectMake(0, 0, 50, 25)];
    if(flag){
        [close setTitle:@"取消收藏" forState:UIControlStateNormal];
    }else{
        [close setTitle:@"收藏" forState:UIControlStateNormal];
    }
//    [close setImage:[UIImage imageNamed:@"客服1"] forState:UIControlStateNormal];
   close.titleLabel.font = [UIFont boldSystemFontOfSize:15];
   [close setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
   UIBarButtonItem *closeItem = [[UIBarButtonItem alloc] initWithCustomView:close];
   self.navigationItem.rightBarButtonItems = @[closeItem];
    [close bk_whenTapped:^{
        if ([USERPHONE length]==0) {
            MKZUSAuthViewController *vc = [MKZUSAuthViewController new];
            [self.navigationController pushViewController:vc animated:YES];
            [SUIUtils makeShortToastAtCenter:@"请先登录"];
            return;
        }
//        NSMutableString * phoneStr=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",@"028-38289396"];
//        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneStr]];
        NSMutableArray *array = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"MyData"]];;
        if(!array){
            array = [NSMutableArray array];
            [array addObject:self.savaDict] ;
        }else{
            if(flag){
                [array removeObject:self.savaDict] ;
            }else{
                [array addObject:self.savaDict] ;
            }
            
        }
        [[NSUserDefaults standardUserDefaults] setObject:array forKey:@"MyData"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [SVProgressHUD show];
        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC));
        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
//            if(flag){
//                [HDUtils makeShortToastWindowAtBottom:@"取消收藏成功"];
//            }else{
//                [HDUtils makeShortToastWindowAtBottom:@"收藏成功"];
//            }
            [self addRigtNav];
        });
    }];

}

- (WKWebView *)getWkwebView{
    return self.webView;
}

- (void)share{
    
    
    //分享的标题
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app名称
     NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
     // app版本
     NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
     // app build版本
     NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
    NSString *textToShare = self.savaDict[@"title"];;
    //分享的图片
    NSString *icon = [NSString stringWithFormat:@"%@",self.savaDict[@"image"]];
    UIImage *imageToShare = [UIImage imageNamed:icon];
    //分享的url
//        NSURL *urlToShare = [NSURL URLWithString:@"http://www.baidu.com"];

    NSArray *activityItems = @[textToShare,imageToShare];

    UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];

    activityVC.excludedActivityTypes = @[UIActivityTypePrint, UIActivityTypeCopyToPasteboard,UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll];

    [self presentViewController:activityVC animated:YES completion:nil];

    //分享之后的回调
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        if (completed) {
            NSLog(@"completed");
            //分享 成功
        } else  {
            NSLog(@"cancled");
            //分享 取消
        }
    };
    
//    NSDictionary *options = self.shareOptions();
//    NSString *title = options[@"title"];
//    NSString *descr = options[@"description"];
//    NSString *iconURL = options[@"iconURL"];
//    NSString *shareURL = nil;
//    if (options[@"shareURL"]) {
//        shareURL = options[@"shareURL"];
//        shareURL = [shareURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    }else {
//        shareURL = [self.url copy];
//    }
//    shareURL = [shareURL stringByAppendingString:[NSString stringWithFormat:@"&title=%@&img=%@",[title stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],iconURL]];
//    [ZKShareAdapter share:shareURL title:title description:descr thumbImage:iconURL platformType:(UMSocialPlatformType_UnKnown) success:^(BOOL isSuccess) {
//        [self userDid:RANK_SHARE];
//    }];
}
// WKNavigationDelegate 页面加载完成之后调用

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    //修改字体大小 300%
    if(self.html.length!=0){
        [ webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '250%'"completionHandler:nil];
    }
    if(self.isShowSave){
        [self addTimer];
    }
    
    
//    //修改字体颜色  #9098b8
//    [ webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= '#222222'"completionHandler:nil];
    
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    DEFINE_WEAK(self)
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        if (object == self.webView) {
            [self.progressView setAlpha:1.0f];
            [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
            if(self.webView.estimatedProgress >= 1.0f) {
                [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                    [wself.progressView setAlpha:0.0f];
                } completion:^(BOOL finished) {
                    [wself.progressView setProgress:0.0f animated:NO];
                }];
            }
        }
        else{
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
    else if ([keyPath isEqualToString:@"title"]){
        if (object == self.webView) {
//            if ([self.title length]==0) {
//                self.navigationItem.title = self.webView.title;
//            }
//            if(self.myTitle.length!=0){
                self.navigationItem.title = self.myTitle;
//            }
         
        }
        else{
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

-(void)onBack{
    if(self.isShowSave){
        NSInteger previousTime = [[NSUserDefaults standardUserDefaults] integerForKey:self.savaDict[@"title"]];
        if(!previousTime){
            previousTime = 0;
        }
        self.time = self.time + previousTime;
        [[NSUserDefaults standardUserDefaults] setInteger:self.time forKey:self.savaDict[@"title"]];
        [[NSUserDefaults standardUserDefaults] synchronize];
        if(self.globalTimer){
            self.globalTimer == nil;
        }
    }
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }else{
//        [super onBack];
    }
}
//-(WMDragView *)dragView{
//    if (!_dragView) {
//        @weakify(self)
//           self.dragView = [[WMDragView alloc] initWithFrame:CGRectMake(kScreenWidth-80,kScreenHeight-TabbarHeight-NavigationbarHeight-100 , 80, 80)];
//           self.dragView.freeRect = CGRectMake(0, 0, kScreenWidth, kScreenHeight-TabbarHeight);
////           self.dragView.backgroundColor = [UIColor redColor];
//           self.dragView.dragEnable = YES;
//           self.dragView.isKeepBounds = YES;
//           self.dragView.hidden = YES;
//           self.dragView.clipsToBounds = NO;
//           [self.view addSubview:self.dragView];
//        self.dragView.backgroundColor = [UIColor whiteColor];
////           self.dragView.clickDragViewBlock = ^(WMDragView *dragView) {
////               @strongify(self)
////               if ([self.webView canGoBack]) {
////                       [self.webView goBack];
////                   }
////           };
//           [self.dragView.closeButton bk_whenTapped:^{
//               @strongify(self)
//               if ([self.webView canGoBack]) {
//                       [self.webView goBack];
//                   }
//           }];
//    }
//    return _dragView;
//}
-(void)dealloc{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView removeObserver:self forKeyPath:@"title"];
    [[self.webView configuration].userContentController removeAllUserScripts];
}



@end
